<template>
	<xn-form-container
		title="质检详情"
		width="70%"
		:visible="visible"
		:destroy-on-close="true"
		@close="onClose"
	>
		<div class="outside-box">
			<a-row :gutter="20">
				<a-col :span="14">
					<div class="lt-box">
						<Audio :audioUrl="audioUrl" :isStop="isStop"/>
					</div>
					<div class="lb-box" :style="{ height: calcLeftBoxHeight }">
						<div
							v-for="(message, index) in messageList"
							:key="index"
							:class="['message', message.speakerRole === 1 ? 'position-left' : 'position-right']"
						>
							<div :class="['message-header', message.speakerRole === 1 ? 'user-header' : 'sys-header']">
								{{
									message.speakerRole === 1 ? '客户' : '系统'
								}}&nbsp;&nbsp;&nbsp;&nbsp;{{ message.chatTime }}
							</div>
							<div
								style="white-space: pre-line;"
								:class="['message-content', message.speakerRole === 1 ? 'user-text-box' : 'sys-text-box']"
							>
								{{ message.content }}
							</div>
						</div>
					</div>
				</a-col>
				<a-col :span="10">
					<div class="rt-box">
						<a-descriptions title="话单详情" size="small" layout="vertical" bordered>
							<a-descriptions-item v-for="item in callRecord" :key="item.id" :label="item.label"
												 :span="item.colSpan">{{ item.value }}
							</a-descriptions-item>
						</a-descriptions>
						<br/>
						<a-descriptions title="质检审核" size="small" bordered>
							<a-descriptions-item label="审核状态" :span="24">
								<a-select
									v-model:value="formData.qualityApproveStatus"
									:disabled="formData.qualityApproveDisabled"
									style="width: 40%"
									placeholder="请选择问题方"
									:options="voiceCheckStatusOptions"/>
							</a-descriptions-item>
							<a-descriptions-item label="审核备注" :span="24">
								<a-textarea
									v-model:value="formData.qualityApproveRemark"
									:disabled="formData.qualityApproveDisabled"
									placeholder="请输入审核备注"
									:auto-size="{ minRows: 4, maxRows: 8 }"/>
							</a-descriptions-item>
						</a-descriptions>
						<a-button type="primary" class="mt-3"
								  v-if="!formData.qualityApproveDisabled && hasPerm('violationQualityApproveBtn')"
								  :loading="saveApproveStatusLoading"
								  @click="saveApproveStatus('quality')">
							保存
						</a-button>
						<br/>
						<br/>
						<a-descriptions title="主管审核" size="small" bordered>
							<a-descriptions-item label="审核状态" :span="24">
								<a-select
									v-model:value="formData.supervisorApproveStatus"
									:disabled="formData.supervisorApproveDisabled"
									style="width: 40%"
									placeholder="请选择问题方"
									:options="voiceCheckStatusOptions"/>
								<a-button class="ml-4" type="primary" danger @click="modalVisible = true"
										  v-if="(formData.supervisorApproveStatus === '1' || formData.supervisorApproveStatus === '3') && !formData.supervisorApproveDisabled">
									客户拉黑
								</a-button>
							</a-descriptions-item>
							<a-descriptions-item label="审核备注" :span="24">
								<a-textarea
									v-model:value="formData.supervisorApproveRemark"
									:disabled="formData.supervisorApproveDisabled"
									placeholder="请输入审核备注"
									:auto-size="{ minRows: 4, maxRows: 8 }"/>
							</a-descriptions-item>
						</a-descriptions>
						<a-button type="primary" class="mt-3"
								  v-if="!formData.supervisorApproveDisabled && hasPerm('violationSupervisorApproveBtn')"
								  :loading="saveApproveStatusLoading"
								  @click="saveApproveStatus('supervisor')">保存
						</a-button>
					</div>
				</a-col>
			</a-row>
		</div>
	</xn-form-container>
	<a-modal
		v-model:open="modalVisible"
		title="客户拉黑"
		:width="500"
		:mask-closable="false"
		:destroy-on-close="true"
		@ok="handleOk"
		@cancel="handleClose"
	>
		<a-form ref="modalFormRef" :model="modalFormData" :rules="modalFormRules" layout="vertical">
			<a-form-item label="重要程度：" name="complainImportant">
				<a-select
					v-model:value="modalFormData.complainImportant"
					placeholder="请选择投诉重要程度"
					:options="complaintsImportanceOptions"/>
			</a-form-item>
			<CompanySelect
				itemType="project"
				colSpan="24"
				:is-reset="resetProject"
				@change-company-select-event="changeCompanySelectEvent"
			/>
			<a-form-item label="投诉内容：" name="complainContent">
				<a-textarea
					v-model:value="modalFormData.complainContent"
					:auto-size="{ minRows: 4, maxRows: 8 }"
					placeholder="请输入投诉内容"
					allow-clear
				/>
			</a-form-item>
		</a-form>
	</a-modal>
</template>

<script setup>
import {computed} from 'vue';
import voiceTextApi from '@/api/qc/voice/text/voiceTextApi';
import Audio from "@/components/AudioView/index.vue";
import htApi from "@/api/tjzy/call/ht/htApi";
import tool from "@/utils/tool";
import voiceCheckApi from "@/api/qc/voice/check/voiceCheckApi";
import CompanySelect from "@/components/Tjzy/Company/CompanySelect.vue";
import {required} from "@/utils/formRules";
import complaintApi from "@/api/tjzy/complaint/complaintApi";

const emit = defineEmits({successful: null})
const visible = ref(false);
const formData = ref({
	qualityApproveStatus: undefined,
	qualityApproveRemark: undefined,
	qualityApproveDisabled: undefined,
	supervisorApproveStatus: undefined,
	supervisorApproveRemark: undefined,
	supervisorApproveDisabled: undefined
})
const modalFormRef = ref()
const modalFormData = ref({
	complainImportant: undefined,
	projectCode: undefined,
	complainContent: undefined
})
const resetProject = ref(false)
const saveApproveStatusLoading = ref(false);
const voiceCheckStatusOptions = tool.dictList('voiceCheckStatus')
const complaintsImportanceOptions = tool.dictList('complaintsImportance')
const audioUrl = ref();
const isStop = ref(false);
const messageList = ref([]);
const callRecord = ref([]);
const headerHeight = 120;
const footerHeight = 60;
const fieldMapping = {
	callId: "通话序列号",
	callee: "被叫",
	agentNum: "坐席账号",
	userName: "坐席姓名",
	deptName: "所属公司",
	callTypeName: "通话类型"
};

const callRecordConvertToItems = (data) => {
	return Object.keys(data).reduce((result, key) => {
		if (fieldMapping[key]) { // 只处理有映射的字段
			let value = data[key];
			if (key === 'userName') {
				value = formData.value.userName;
			}
			result.push({
				key: result.length + 1,
				label: fieldMapping[key],
				value: value
			});
		}
		return result;
	}, []);
};

const calcLeftBoxHeight = computed(() => {
	return `calc(100vh - ${headerHeight + footerHeight}px)`;
});

const modalVisible = ref(false);
const modalFormRules = {
	complainImportant: [required('请选择重要程度')],
	projectCode: [required('请选择所属项目')],
	complainContent: [required('请输入投诉内容')]
}
// 打开抽屉
const onOpen = (record) => {
	console.log(record.supervisorApproveStatus)
	formData.value = record
	visible.value = true;
	audioUrl.value = record.fileUrl;
	formData.value.qualityApproveDisabled = record.qualityApproveStatus != null && record.qualityApproveStatus > 0
	formData.value.supervisorApproveDisabled = record.supervisorApproveStatus != null && record.supervisorApproveStatus > 0
	voiceTextApi.getTextByCallId(record.callId).then((res) => {
		messageList.value = res;
	});
	htApi.callRecordPage({
		current: 1,
		size: 1,
		beginTime: '2024-10-01 00:00:00',
		endTime: '2025-02-06 23:59:59',
		callId: record.callId
	}).then(res => {
		if (res) {
			if (record.deptName) {
				res.records[0].deptName = record.deptName
			}
			callRecord.value = callRecordConvertToItems(res.records[0] || {}, record.userName);
		}
	})
};

// 关闭抽屉
const onClose = () => {
	visible.value = false;
	formData.value = {}
	stopAudio();
};

// 停止音频播放
const stopAudio = () => {
	isStop.value = true;
	setTimeout(() => {
		isStop.value = false;
	}, 500);
};

const saveApproveStatus = (type) => {
	saveApproveStatusLoading.value = true;
	let obj = {
		id: formData.value.id,
		type: type,
	}
	if (type === 'quality') {
		obj.qualityApproveStatus = formData.value.qualityApproveStatus
		obj.qualityApproveRemark = formData.value.qualityApproveRemark
	}
	if (type === 'supervisor') {
		obj.supervisorApproveStatus = formData.value.supervisorApproveStatus
		obj.supervisorApproveRemark = formData.value.supervisorApproveRemark
	}
	voiceCheckApi.modifyViolationStatus(obj).then((res) => {
		onClose()
		emit('successful')
		saveApproveStatusLoading.value = false
	})
}

const changeCompanySelectEvent = (val) => {
	modalFormData.value.projectCode = val.projectCode;
}

const handleOk = () => {
	//
	complaintApi.checkComplaintUser()
	handleClose();
}

const handleClose = () => {
	modalFormRef.value.resetFields();
	resetProject.value = true;
	setTimeout(() => {
		resetProject.value = false
	}, 200)
}

// 暴露方法供父组件调用
defineExpose({
	onOpen
});
</script>

<style scoped>
.lt-box {
	margin-bottom: 10px;
}

.lb-box {
	overflow-y: auto;
	padding: 10px;
	border: 1px solid #ccc;
}

.rt-box {
}

.message {
	margin-bottom: 10px;
}

.position-left {
	text-align: left;
	margin-right: auto;
}

.position-right {
	text-align: right;
	margin-left: auto;
}

.sys-header {
	color: #ff4d4f;
}

.user-header {
	color: #1890ff;
}

.sys-text-box {
	background-color: #00ff80;
	max-width: 70%;
	margin-left: auto;
	border-radius: 5px;
	padding: 5px;
}

.user-text-box {
	background-color: #ffffff;
	border: 1px solid #ddd;
	max-width: 70%;
	margin-right: auto;
	border-radius: 5px;
	padding: 5px;
}

/* 自定义滚动条样式 */
.lb-box::-webkit-scrollbar {
	width: 8px;
}

.lb-box::-webkit-scrollbar-track {
	background: #f1f1f1;
}

.lb-box::-webkit-scrollbar-thumb {
	background: #888;
	border-radius: 4px;
}

.lb-box::-webkit-scrollbar-thumb:hover {
	background: #555;
}
</style>
